<template>
	<div class="wrapper">
		<!-- header部分 -->
		<header>
			<p>在线支付</p>
		</header>

		<!-- 订单信息部分 -->
		<h3>订单信息：</h3>
		<div class="order-info">
			<p>
				{{ orderData.business?.businessName }}
				<i class="fa fa-caret-down" @click="toggleDetail"></i>
			</p>
			<p>&#165;{{ (orderData.orderTotal - pointsDeduction).toFixed(1) }}</p>
		</div>

		<!-- 订单明细部分 -->
		<ul class="order-detail" v-show="showDetail">
			<li v-for="item in orderData.orderItems" :key="item.id">
				<p>{{ item.food?.foodName }} x {{ item.quantity }}</p>
				<p>&#165;{{ (item.food?.foodPrice * item.quantity).toFixed(1) }}</p>
			</li>
			<li>
				<p>配送费</p>
				<p>&#165;{{ orderData.business?.deliveryPrice?.toFixed(1) }}</p>
			</li>
			<li>
				<p>积分抵扣</p>
				<p>&#165;{{ -pointsDeduction.toFixed(1) }}</p>
			</li>
		</ul>

		<!-- 钱包余额显示 -->
		<div class="wallet-balance" v-if="hasWallet">
			<p>钱包余额：&#165;{{ walletBalance.toFixed(2) }}</p>
		</div>

		<!-- 支付方式部分 -->
		<ul class="payment-type">
			<li @click="selectPayment('wallet')" :class="{active: selectedPayment === 'wallet'}">
				<span>钱包支付</span>
				<i class="fa fa-check-circle"></i>
			</li>
		</ul>

		<!-- 商家钱包信息（仅用于测试） -->
		<div class="merchant-info" v-if="showDebugInfo">
			<p>商家钱包ID：{{ merchantWalletId }}</p>
		</div>
		
		<div class="payment-button">
			<button @click="confirmPayment" :disabled="isProcessing || !hasWallet">
				{{ isProcessing ? '处理中...' : hasWallet ? '确认支付' : '请先开通钱包' }}
			</button>
		</div>

		<!-- 底部菜单部分 -->
		<Footer></Footer>
	</div>
</template>

<script>
import Footer from '../components/Footer.vue';

export default {
	name: 'Payment',
	data() {
		return {
			orderId: this.$route.query.orderId,
			orderData: {
				business: {},
				orderItems: []
			},
			showDetail: false,
			selectedPayment: 'wallet',
			walletBalance: 0,
			totalPoints: 0,
			isProcessing: false,
			pointsDeduction: 0,
			hasWallet: false,
			userWalletId: null,
			merchantWalletId: 1, // 假设商家钱包ID为1，实际应从订单或商家信息获取
			showDebugInfo: false // 生产环境设为false
		}
	},
	async created() {
		this.user = this.$getSessionStorage('user');
		
		if (!this.user?.userId) {
			this.$router.push('/login');
			return;
		}

		await this.loadOrderData();
		await this.loadWalletInfo();
		await this.loadUserPoints();
	},
	methods: {
		async loadOrderData() {
			try {
				const response = await this.$axios.get(`/api/orders/${this.orderId}`);
				
				if (response.data.success) {
					this.orderData = response.data.data;
					this.calculatePointsDeduction();
					
					// 从订单信息中获取商家钱包ID（如果有的话）
					if (this.orderData.business?.walletId) {
						this.merchantWalletId = this.orderData.business.walletId;
					}
				} else {
					console.error('获取订单失败:', response.data.message);
					alert('获取订单失败: ' + response.data.message);
				}
			} catch (error) {
				console.error('获取订单失败:', error);
				this.handleApiError(error, '获取订单');
			}
		},
		
	async loadWalletInfo() {
		try {
			// 使用新的API: GET /api/virtual-wallets/user/{userId}
			const walletResponse = await this.$axios.get(`/api/virtual-wallets/user/${this.user.userId}`);
			
			if (walletResponse.data.success && walletResponse.data.data) {
				this.walletBalance = walletResponse.data.data.balance || 0;
				this.userWalletId = walletResponse.data.data.walletId;
				this.hasWallet = true;
				console.log('钱包信息加载成功:', walletResponse.data.data);
			} else {
				this.hasWallet = false;
				console.log('用户未开通钱包');
			}
		} catch (error) {
			console.error('获取钱包信息失败:', error);
			// 404错误表示用户还没有钱包
			if (error.response?.status === 404) {
				this.hasWallet = false;
				console.log('用户未开通钱包');
			} else {
				this.hasWallet = false;
			}
		}
	},
		
		async loadUserPoints() {
			try {
				const response = await this.$axios.get('/api/credits/total', {
					params: {
						userId: this.user.userId
					}
				});
				
				if (response.data.success) {
					this.totalPoints = response.data.data || 0;
					this.calculatePointsDeduction();
				} else {
					console.error('获取积分失败:', response.data.message);
				}
			} catch (error) {
				console.error('获取积分失败:', error);
			}
		},
		
		calculatePointsDeduction() {
			// 计算积分抵扣金额 (1积分=0.1元)
			const maxDeduction = this.totalPoints * 0.1;
			this.pointsDeduction = Math.min(maxDeduction, this.orderData.orderTotal || 0);
		},
		
		toggleDetail() {
			this.showDetail = !this.showDetail;
		},
		
		selectPayment(type) {
			this.selectedPayment = type;
		},
		
		async confirmPayment() {
			if (this.isProcessing) return;
			
			// 检查钱包状态
			if (!this.hasWallet) {
				alert('请先开通钱包功能');
				this.$router.push('/myWallet');
				return;
			}
			
            const payableAmount = (this.orderData.orderTotal || 0) - this.pointsDeduction;
			
			if (!confirm(`确认支付 ¥${payableAmount.toFixed(2)}？`)) {
				return;
			}
			
			this.isProcessing = true;
			
		try {
			// 使用正确的API: POST /api/virtual-wallets/pay-order（冻结资金）
            const headers = this.user?.token ? { Authorization: `Bearer ${this.user.token}` } : {};
            const payOrderResponse = await this.$axios.post('/api/virtual-wallets/pay-order', null, {
                params: {
                    walletId: this.userWalletId,
                    amount: payableAmount,
                    orderId: this.orderId
                },
                headers
            });
			
			console.log('支付订单响应:', payOrderResponse.data);
			
			if (payOrderResponse.data.success) {
				// 支付成功后，更新订单状态为已支付(2)
				try {
					await this.$axios.put(`/api/orders/${this.orderId}/state`, null, {
						params: { state: 2 }
					});
					console.log('订单状态已更新为已支付');
				} catch (stateError) {
					console.error('更新订单状态失败:', stateError);
					// 即使更新状态失败，支付已成功，继续流程
				}
				
				this.showSuccessMessage('支付成功！资金已冻结，确认收货后将转给商家。');
				
				// 跳转到支付成功页面
				this.$router.push({
					path: '/paySuccess',
					query: {
						orderId: this.orderId,
						amount: payableAmount,
						paymentMethod: 'wallet'
					}
				});
			} else {
				this.showErrorMessage('支付失败: ' + (payOrderResponse.data.message || '未知错误'));
			}
			} catch (error) {
				console.error('支付失败:', error);
				this.handleTransferError(error);
			} finally {
				this.isProcessing = false;
			}
		},
		
		// 专门处理转账错误
		handleTransferError(error) {
			console.error('转账失败:', {
				message: error.message,
				status: error.response?.status,
				data: error.response?.data
			});
			
			if (error.response?.status === 400) {
				const errorMsg = error.response.data?.message || '请求参数错误';
				if (errorMsg.includes('余额不足')) {
					alert('钱包余额不足，请充值或选择其他支付方式');
				} else if (errorMsg.includes('不存在')) {
					alert('钱包不存在，请检查钱包状态');
				} else {
					alert(`支付失败: ${errorMsg}`);
				}
			} else if (error.response?.status === 500) {
				alert('服务器内部错误，请稍后再试');
			} else if (error.response?.status === 401) {
				alert('用户未登录或会话已过期');
				this.$router.push('/login');
			} else if (error.response?.data?.message) {
				alert(`支付失败: ${error.response.data.message}`);
			} else {
				alert('支付失败，请检查网络连接');
			}
		},
		
		showSuccessMessage(message) {
			alert(message);
		},
		
		showErrorMessage(message) {
			alert(message);
		},
		
		handleApiError(error, operation) {
			console.error(`${operation}失败:`, {
				message: error.message,
				status: error.response?.status,
				data: error.response?.data
			});
			
			if (error.response?.status === 500) {
				alert('服务器内部错误，请稍后再试');
			} else if (error.response?.status === 404) {
				alert('请求的资源不存在');
			} else if (error.response?.status === 401) {
				alert('用户未登录或会话已过期');
				this.$router.push('/login');
			} else if (error.response?.data?.message) {
				alert(`${operation}失败: ${error.response.data.message}`);
			} else {
				alert(`${operation}失败，请检查网络连接`);
			}
		}
	},
	components: {
		Footer
	}
}
</script>

<style scoped>
	/****************** 总容器 ******************/
	.wrapper {
		width: 100%;
		height: 100%;
		background-color: #f5f5f5;
	}

	/****************** header部分 ******************/
	.wrapper header {
		width: 100%;
		height: 12vw;
		background-color: #0097FF;
		color: #fff;
		font-size: 4.8vw;
		position: fixed;
		left: 0;
		top: 0;
		z-index: 1000;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	/****************** 订单信息部分 ******************/
	.wrapper h3 {
		margin-top: 12vw;
		box-sizing: border-box;
		padding: 4vw 4vw 0;
		font-size: 4vw;
		font-weight: 300;
		color: #999;
	}

	.wrapper .order-info {
		box-sizing: border-box;
		padding: 4vw;
		font-size: 4vw;
		color: #666;
		background-color: #fff;
		display: flex;
		justify-content: space-between;
		align-items: center;
		border-bottom: 1px solid #eee;
	}

	.wrapper .order-info p:last-child {
		color: orangered;
		font-weight: bold;
	}

	/****************** 订单明细部分 ******************/
	.wrapper .order-detail {
		width: 100%;
		background-color: #fff;
		list-style: none;
		padding: 0;
		margin: 0;
	}

	.wrapper .order-detail li {
		width: 100%;
		box-sizing: border-box;
		padding: 3vw 4vw;
		display: flex;
		justify-content: space-between;
		align-items: center;
		border-bottom: 1px solid #f0f0f0;
	}

	.wrapper .order-detail li p {
		font-size: 3.5vw;
		color: #666;
		margin: 0;
	}

	/****************** 钱包余额显示 ******************/
	.wrapper .wallet-balance {
		box-sizing: border-box;
		padding: 3vw 4vw;
		background-color: #fff;
		border-bottom: 1px solid #eee;
	}

	.wrapper .wallet-balance p {
		font-size: 3.8vw;
		color: #333;
		margin: 0;
		font-weight: 500;
	}

	/****************** 支付方式部分 ******************/
	.wrapper .payment-type {
		width: 100%;
		margin-top: 4vw;
		background-color: #fff;
		list-style: none;
		padding: 0;
	}

	.wrapper .payment-type li {
		width: 100%;
		box-sizing: border-box;
		padding: 4vw;
		display: flex;
		justify-content: space-between;
		align-items: center;
		border-bottom: 1px solid #eee;
		cursor: pointer;
		transition: background-color 0.3s;
	}

	.wrapper .payment-type li:hover {
		background-color: #f8f9fa;
	}

	.wrapper .payment-type li.active {
		background-color: #f0f7ff;
	}

	.wrapper .payment-type li span {
		font-size: 4vw;
		color: #333;
		font-weight: 500;
	}

	.wrapper .payment-type li .fa-check-circle {
		font-size: 5vw;
		color: #38CA73;
		visibility: hidden;
	}

	.wrapper .payment-type li.active .fa-check-circle {
		visibility: visible;
	}

	/****************** 商家信息（调试用） ******************/
	.wrapper .merchant-info {
		box-sizing: border-box;
		padding: 2vw 4vw;
		background-color: #fff8e1;
		border-left: 4px solid #ffc107;
		margin: 2vw 4vw 0;
		border-radius: 4px;
	}

	.wrapper .merchant-info p {
		font-size: 3.2vw;
		color: #666;
		margin: 0;
		font-family: monospace;
	}

	/****************** 支付按钮部分 ******************/
	.wrapper .payment-button {
		width: 100%;
		box-sizing: border-box;
		padding: 4vw;
		margin-top: 4vw;
	}

	.wrapper .payment-button button {
		width: 100%;
		height: 12vw;
		border: none;
		outline: none;
		border-radius: 6px;
		background-color: #38CA73;
		color: #fff;
		font-size: 4.5vw;
		font-weight: bold;
		cursor: pointer;
		transition: all 0.3s;
	}

	.wrapper .payment-button button:hover:not(:disabled) {
		background-color: #2db863;
		transform: translateY(-1px);
		box-shadow: 0 2px 8px rgba(56, 202, 115, 0.3);
	}

	.wrapper .payment-button button:disabled {
		background-color: #cccccc;
		cursor: not-allowed;
		transform: none;
		box-shadow: none;
	}

	/****************** 响应式设计 ******************/
	@media (min-width: 768px) {
		.wrapper header {
			height: 60px;
			font-size: 20px;
		}
		
		.wrapper h3 {
			margin-top: 60px;
			font-size: 16px;
			padding: 20px 20px 0;
		}
		
		.wrapper .order-info,
		.wrapper .wallet-balance,
		.wrapper .payment-type li {
			padding: 15px 20px;
			font-size: 16px;
		}
		
		.wrapper .order-detail li {
			padding: 12px 20px;
		}
		
		.wrapper .order-detail li p,
		.wrapper .wallet-balance p {
			font-size: 14px;
		}
		
		.wrapper .payment-type li span {
			font-size: 16px;
		}
		
		.wrapper .payment-button {
			padding: 20px;
		}
		
		.wrapper .payment-button button {
			height: 50px;
			font-size: 18px;
			max-width: 400px;
			margin: 0 auto;
			display: block;
		}
	}
</style>
